using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
using System.Collections.Specialized;
using DBComponent;
using SigmaStock_Components;

namespace project
{
    public partial class BuyMagazine : Form
    {
        OleDbConnection conn;
        OleDbCommand command;
        string query;
        String pname;
        int amt_purchased;        
        AutoCompleteStringCollection namesCollection =new AutoCompleteStringCollection();
        public List<string> magazine_names = new List<string>();

        public BuyMagazine()
        {
                
         //  populateStrings();
            query = "";
           InitializeComponent();
           dbconnection();
           if (Form3.purchase_list.Count > 0)
           {
               DBClass obj = Form3.purchase_list[0];
               this.pub_name.Text = obj.PNAME;
               InsertIntoTemp();
           }
           else
               dataGridView1.Visible = false;
          
            currdate();



        }

        private void InsertIntoTemp()
        {

            query = "delete * from temp;";
            command.CommandText = query;
            command.Connection = conn;
            command.ExecuteNonQuery();
            int sno=0;
            foreach (DBClass obj in Form3.purchase_list)
            {
                sno++;
                query = "insert into temp(SNO,MNAME,MDATE,MPRICE,QTY,TOTAL) VALUES('" + sno + "','" + obj.MNAME + "','" + obj.MDATE + "','" + obj.price + "','" + obj.qty + "','" + (obj.price * obj.qty) + "');";
                command.CommandText = query;
                command.ExecuteNonQuery();
            }
            String s;
            s = "Select * from temp";
            OleDbCommand cmd1 = new OleDbCommand(s, conn);
            OleDbDataAdapter da = new OleDbDataAdapter(s, conn);
            DataSet ds = new DataSet();
            da.Fill(ds, "temp");
            dataGridView1.Visible = true;
            dataGridView1.DataSource = ds;
            dataGridView1.DataMember = "temp";
            tempBindingSource.ResetBindings(false);
            this.Refresh();
        }

    /*    void populateStrings()
        {
           str_collection = new AutoCompleteStringCollection();
            OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=..\\..\\mag_dealer.mdb");
            conn.Open();
            string queryString = "select MNAME from magazine";
            OleDbCommand command = new OleDbCommand(queryString, conn);

            OleDbDataReader reader = command.ExecuteReader();
            while (reader.Read())
            {
                str_collection.Add(reader[0].ToString());
                Console.WriteLine(reader[0]);
           }

           foreach (string s in str_collection)
           {
               Console.WriteLine("mag =" + s);
           }

        }*/

        public void currdate()
        {
            DateTime d = DateTime.Now;
            label11.Text = d.ToString();
        }

        private void dbconnection()
        {
            conn = Mag_DealerDB.dbconnection();
            conn.Open();
            command = new OleDbCommand();
            command.Connection = conn;
        }

        public void UpdateFormDetails()
        {
            String mname = mag_name.Text;

            try
            {
                String query = "select PRICE,PNAME from MAGAZINE where MNAME= '" + mname + "'";
                OleDbCommand command = new OleDbCommand(query, conn);
                OleDbDataReader reader = command.ExecuteReader();
                while (reader.Read())
                {
                    textBox4.Text = reader[0].ToString();
                    pub_name.Text = reader[1].ToString();
                    amt_purchased = int.Parse(qty.Text) * int.Parse(textBox4.Text);
                    textBox5.Text = amt_purchased + "";
                    pname = pub_name.Text;
                }
                                
            }
            catch (Exception ex)
            { }
        }

        /*public void check_pub_due()
        {
            int amt_due=0;
            int deposit=0;
            try
            {
                String query = "select DEPOSIT,AMOUNT_DUE FROM publisher_credit where PNAME='"+pname+"'";
                OleDbCommand command = new OleDbCommand(query, conn);
                OleDbDataReader reader = command.ExecuteReader();
                while (reader.Read())
                {
                    deposit = int.Parse(reader[0].ToString());
                    amt_due = int.Parse(reader[1].ToString());
                }

                amt_due += amt_purchased;
                if (amt_due > deposit)
                {
                    MessageBox.Show("Warning : Credit limit crossed ");
                    
                }
                reader.Close();                

                query="update publisher_credit set AMOUNT_DUE='"+amt_due+"'";
                command.CommandText = query;
                command.Connection = conn;
                command.ExecuteNonQuery();
                //Console.WriteLine(amt_due);

            }
            catch (Exception ex) { }
 
        }*/

        private void UpdatePurchaseList()
        {
            DBClass obj = new DBClass();
            obj.MNAME = this.mag_name.Text;
            obj.PNAME = pub_name.Text;
            obj.price = int.Parse(textBox4.Text);
            obj.qty = int.Parse(qty.Text);
            DateTime d = new DateTime(dateTimePicker2.Value.Year, dateTimePicker2.Value.Month, dateTimePicker2.Value.Day);
            obj.MDATE = d;
            Form3.purchase_list.Add(obj);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (BuyMagazine_Validate())
            {
                UpdateFormDetails();
                UpdatePurchaseList();
                Program.Invoke(this, "project.BuyMagazine");
            }
           // curr.Show();

            
        }

        private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)13)
            {
                dbconnection();
                UpdateFormDetails();
             //   check_pub_due();
            }
        }

        private void textBox3_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)13)
            {
                dbconnection();
                UpdateFormDetails();
                //check_pub_due();
            }
        }

        private bool BuyMagazine_Validate()
        {
            //to check if mag_name is not empty
            //to see if it is present in database            
            //to see if  publisher sells magazine
            //to see quantity is not empty and is positive
            bool flag = true;

            if (magazine_names.Count == 0)
            {
                query = "select MNAME from magazine;";
                command.Connection = conn;
                command.CommandText = query;
                OleDbDataReader reader = command.ExecuteReader();
                while (reader.Read())
                {
                    magazine_names.Add(reader[0].ToString());

                }
                
            }

            if (!(magazine_names.Contains(mag_name.Text)))
            {
              
                Console.Beep();
                textBox1.Visible = true;
                textBox1.Text = "Check magazine name";
                //flag = false;
                return false;
            }


            if (String.IsNullOrEmpty(mag_name.Text) || !(Validation.IsAlphaNumeric(mag_name.Text)))
            {
                Console.Beep();
                textBox1.Visible = true;
                textBox1.Text = "Check magazine name";
                //flag = false;
                return false;
            }
            //see if publisher sells magazine
            if (Form3.purchase_list.Count > 0)
            {
                if (Form3.magazine_list.Count == 0)
                {
                    //fill list
                    query = "select MNAME from magazine where PNAME='" + pub_name.Text + "';";
                    OleDbCommand command = new OleDbCommand(query, conn);
                    OleDbDataReader reader = command.ExecuteReader();
                    while (reader.Read())
                    {
                        Form3.magazine_list.Add(reader[0].ToString());
                    }
                    
                }
                if (!(Form3.magazine_list.Contains(mag_name.Text)))
                {
                    Console.Beep();
                    textBox1.Visible = true;
                    textBox1.Text = "Magazine not sold by current publisher";
                    //flag = false;
                    return false;
                }

            }

            //see if quantity is not empty and positive
            if (String.IsNullOrEmpty(qty.Text)|| !(Validation.IsPositiveNumber(qty.Text)))
            {
                Console.Beep();
                textBox1.Visible = true;
                textBox1.Text = "Enter the quantity";
                //flag = false;
                return false;
            }



            return true;
            //return flag;
        }

        private void button3_Click(object sender, EventArgs e)
        {
            if (BuyMagazine_Validate())
            {
                UpdateFormDetails();
                
            }
            
            //check_pub_due();
           
            //this.textBox2.Text = Form3.temp[1];
        }

        private void mag_name_TextChanged(object sender, EventArgs e)
        {

        }

        private void BuyMagazine_Load(object sender, EventArgs e)
        {
            // TODO: This line of code loads data into the 'mag_dealerDataSet.temp' table. You can move, or remove it, as needed.
            this.tempTableAdapter.Fill(this.mag_dealerDataSet.temp);
            try
            {
                dbconnection();
                OleDbDataReader reader;
                command.CommandText = "select MNAME from magazine;";
                reader = command.ExecuteReader();
                while (reader.Read())
                {
                    namesCollection.Add(reader[0].ToString());
                }
                
                reader.Close();
                mag_name.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
                mag_name.AutoCompleteSource = AutoCompleteSource.CustomSource;                
                mag_name.AutoCompleteCustomSource = namesCollection;
            } 
            catch(Exception ex)
            {
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (Form3.purchase_list.Count > 0 && mag_name.Text.Equals("") && qty.Text.Equals(""))
            {
                Program.Invoke(this, "project.Payment");
            }
            else if (BuyMagazine_Validate())
            {
                UpdateFormDetails();
                UpdatePurchaseList();
                Program.Invoke(this, "project.Payment");
            }
          
        }

        private void BuyMagazine_FormClosed(object sender, FormClosedEventArgs e)
        {
          //  Form3.DataReset();
            if (Application.OpenForms.Count == 1)
            {
                Program.main_form.Show();
            }
        }

        private void dateTimePicker2_ValueChanged(object sender, EventArgs e)
        {

        }

        private void button4_Click(object sender, EventArgs e)
        {
            mag_name.Text = "";
            qty.Text = "";
            pub_name.Text = "";
            textBox4.Text = "";
            textBox5.Text = "";



        }

 


    }
}